<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/1/9 0009
 * Time: 11:15
 */

namespace application\index\controller;


use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\News;
use EasyWeChat\Message\Text;
use think\Config;
use think\Controller;
use think\Db;
use think\Request;

class WechatController extends Controller
{
    public function index(){
        if (Request::instance()->isPost())
            $id = $this->request->param('id');
        $data = Db::name('wechatapp')->where('app_id', $id)->find();
        $app_url = ROOT_PATH;
        $config = [
            'debug' => true,
            'app_id' => $data['appid'],  //wxa32e12e8fb8b21ca
            'secret' => $data['appsecret'],//20c211941b9db00a2e5cff0efa532d7b
            'token' => $data['token'],       //123456
            'aes_key' => '',                    // EncodingAESKey，安全模式与兼容模式下请一定要填写！！！
            'log' => [
                'level' => 'debug',
                'permission' => 0777,
                'file' => $app_url . '/runtime/easywechat.log',
            ],
        ];
        $app = new Application($config);
// 从项目实例中得到服务端应用实例。
        $server = $app->server;
        if($data['app_type'] == '0'){
            $server->setMessageHandler(function ($message) {
                $id = $this->request->param('id');
                $map['reply_keywords'] = $message->Content;
                $map['app_id'] = $id;
                $reply_data = Db::name('replyset')->where($map)->find();
                switch ($message->MsgType) {
                    case 'event':
                        return '收到事件消息';
                        break;
                    case 'text';
                           return $reply_data['reply_answer'];
                        break;
                    default:
                     return '收到其它消息';
                     break;
                }
                return '欢迎关注';
            });
            $server->serve()->send();
        }else{
            $message = $server->getMessage();
            file_put_contents($app_url.'/runtime/test.txt',var_export($message,true));
            $openId = $message['FromUserName'];
            file_put_contents($app_url.'/runtime/test2.txt',$openId);
             if($message['MsgType'] == 'text'){
                 $map['reply_keywords'] = $message['Content'];
                 $map['app_id'] = $id;
                 $reply_data = Db::name('replyset')->where($map)->select();
                 Db::name('channel')->where($map)->setInc('add_follow',1);
             }elseif($message['MsgType'] == 'event'){
                 $map['app_id'] = $id;
                 $map['reply_keywords'] = $message['EventKey'];
                 Db::name('channel')->where($map)->setInc('add_follow',1);
                 $reply_data = Db::name('replyset')->where($map)->select();
             }
            if($reply_data){
                foreach ($reply_data as $k=>$v){
                    if($v['reply_type'] == '0') {
                        $message2 = new Text(['content' => $v['reply_answer']]);
                        $app->staff->message($message2)->to($openId)->send();
                    }elseif($v['reply_type'] == '1'){
                        $url = Config::get('web_url');
                        $news1 = new News([ 'title' => $v['title'], 'url' => $v['url'], 'image' =>$url.$v['image_url'], 'description' =>$v['description']]);
                        $app->staff->message($news1)->to($openId)->send();
                    }
                }
            }else{
                $message2 = new Text(['content' =>'暂无信息']);
                $app->staff->message($message2)->to($openId)->send();
            }
          //  file_put_contents($app_url.'/runtime/test.txt',var_export($message,true));
//            $message2 = new Text(['content' => 'Hello world!']);
//            $app->staff->message($message2)->to($openId)->send();
//            $message3= new Text(['content' => 'Hello world2!']);
//            $app->staff->message($message3)->to($openId)->send();
        }

        // $server->serve()->send();
//        $server->setMessageHandler(function ($message) {
//            $app_url = ROOT_PATH;
//            $openId = $message->FromUserName;
//            file_put_contents($app_url.'/runtime/test.txt',$openId,FILE_APPEND);
//        });


      //  $app->staff->message($mes)->to($openId)->send();

//   /*     $server->setMessageHandler(function ($message) {
//            // $message->FromUserName // 用户的 openid
//            // $message->MsgType // 消息类型：event, text....
//             //$message->Content  文本消息内容
//            $id = $this->request->param('id');
//            $map['reply_keywords'] = $message->Content;
//            $map['app_id'] = $id;
//            $data = Db::name('replyset')->where($map)->select();
//           // $txtarr = array();
////          if(!empty($data)) {
////            foreach ($data as $k=>$v){
////                if($v['reply_type'] == '0'){
////                        $txtarr[$k] = new Text(['content'=>$v['reply_answer']]);
////                    //$txtarr[$k] = $v['reply_answer']; //回复的文本信息；
////                }
////             }
////            }
//
//           // $app_url = ROOT_PATH;
//         // file_put_contents($app_url.'/runtime/arr.txt',var_export($txtarr,true));
//        /*    switch ($message->MsgType) {
//                case 'event':
//                    return '收到事件消息';
//                    break;
//                case 'text':
//                    $news1 = new News(['title'=>'1']);
//                    $news2 = new News(['title'=>'23434']);
//                    return [$news1,$news2];
//                    break;
//                case 'image':
//                    return '收到图片消息';
//                    break;
//                case 'voice':
//                    return '收到语音消息';
//                    break;
//                case 'video':
//                    return '收到视频消息';
//                    break;
//                case 'location':
//                    return '收到坐标消息';
//                    break;
//                case 'link':
//                    return '收到链接消息';
//                    break;
//                // ... 其它消息
//                default:
//                    return '收到其它消息';
//                    break;
//            }*/
//
//            $news1 = new News([ 'title' => '李白，今朝有酒今朝醉',
//                'url' => 'http://stark.wang',
//                'image' => 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1512627415601&di=a48be9abc9661620472cf49c9388f221&imgtype=0&src=http%3A%2F%2Fi1.17173cdn.com%2F2fhnvk%2FYWxqaGBf%2Fcms3%2FXivJLTbldqzvDcv.jpg',
//                'description' => '今朝有酒今朝醉，李白就是一个诗人']);
//            $news2 = new News([        'title' => '安琪拉',
//                'url' => 'http://stark.wang',
//                'image' => 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1513221767&di=112afbccd30f26c20392a7dfff06926a&imgtype=jpg&er=1&src=http%3A%2F%2Fqtimg.bdstatic.com%2Fhiapk%2Fgame%2F201707%2F04%2F595af6d2285d9.jpg',
//                'description' => 'hi 安琪拉！！！']);
//            return [$news1,$news2];
//          //  return '欢迎关注'.$id;
//        });
//
//      $server->serve()->send();*/
       // exit();
    }
}